package com.mconnect.msurvey.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;

import com.mconnect.msurvey.model.User;
import com.mconnect.msurvey.util.HibernateUtil;

public class UserManager extends HibernateUtil{
	
	public User register(User user){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
       session.getTransaction().begin();
        user.setType("u");
        Timestamp data = new Timestamp(new java.util.Date().getTime());
        user.setLastLogoutDate(data);
        user.setLoginDate(data);
        user.setLogoutDate(data);
        
        session.save(user);
        
        session.getTransaction().commit();
       
		return user;
	}
	
	/**
	 * Sprawdza czy podany uzytkownik istnieje w bazie. Jezeli uzytkownik istnieje to zwraca go, w przeciwnym wypadku null.
	 * @param login
	 * @param password
	 * @return 
	 */
	@SuppressWarnings("unchecked")
	public User getUserIfRegister(String login, String password){
		 Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.getTransaction().begin();
         List<User> listOfUsers = new ArrayList<User>();
         Query q = session.createQuery("from User where login='"+ login + "' and pass='" + password + "' and type='u'");
         listOfUsers = q.list();
         
         User user = null;
         if(!listOfUsers.isEmpty()){
                 for (User users : listOfUsers) {
                         user = (User) session.load(User.class, users.getId_user());
                 }
                 
         }
         session.getTransaction().commit();
        
         return user;
		
	}
	@SuppressWarnings("deprecation")
	public String getCurrentTime(){
		java.util.Date date = new java.util.Date();
		String minutes = "" + date.getMinutes();
		if(date.getMinutes() < 10){
			minutes = "0" + date.getMinutes();
		}
		String currentTime = date.getHours() + ":" + minutes + ":" + date.getSeconds();
		return currentTime;
	}
	
	public User updateLoginTime(String currentTime, int id_user){
		 Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.getTransaction().begin();
         User user = (User) session.load(User.class, id_user);
         
         Timestamp data = new Timestamp(new java.util.Date().getTime());
         user.setLoginDate(data);
         session.update(user);
         session.getTransaction().commit();
        
         return user;
	}
	
	public User updateLogoutTime(String currentTime, int id_user){
		 Session session = HibernateUtil.getSessionFactory().getCurrentSession();
       session.getTransaction().begin();
        User user = (User) session.load(User.class, id_user);
        user.setLastLogoutDate(user.getLogoutDate());
        Timestamp data = new Timestamp(new java.util.Date().getTime());
        user.setLogoutDate(data);
        session.update(user);
        session.getTransaction().commit();
       
        return user;
	}
	
	public User getAdminIfRegister(String login, String password){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
       session.getTransaction().begin();
        List<User> listOfUsers = new ArrayList<User>();
        Query q = session.createQuery("from User where login='"+ login + "' and pass='" + password + "' and type='a'");
        listOfUsers = q.list();
        
        User user = null;
        if(!listOfUsers.isEmpty()){
                for (User users : listOfUsers) {
                        user = (User) session.load(User.class, users.getId_user());
                }
                
        }
        session.getTransaction().commit();
       
        return user;
		
	}
	
	@SuppressWarnings("unchecked")
	public List<String> getLoginList(){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
       session.getTransaction().begin();
        List<String> loginsList = new ArrayList<String>();
        loginsList = session.createSQLQuery("select login from user where type='u'").list();
        session.getTransaction().commit();
       
		return loginsList;
	}
	
	@SuppressWarnings("unchecked")
	public Set<User> getUsersFromDB(){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
       session.getTransaction().begin();
        
        List<User> loginsList = new ArrayList<User>();
        loginsList = session.createQuery("from User where type='u' ").list();
        
        List<User> planList = new ArrayList<User>();
        planList = session.createQuery("select DISTINCT s.users from SurveyPlan s LEFT JOIN s.users where s.status='w trakcie' ").list();
        Set<User> finalList = new HashSet<User>();
        if(!loginsList.isEmpty() && !planList.isEmpty()){
        	for (User login : loginsList) {
				if(!planList.contains(login)){
					finalList.add(login);
				}
			}
        }else{
        	finalList.addAll(loginsList);
        }
        
        session.getTransaction().commit();
       
		return finalList;
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getAllUsersFromDB(){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
       session.getTransaction().begin();
        
        List<User> loginsList = new ArrayList<User>();
        loginsList = session.createQuery("from User where type='u' ").list();
        
        session.getTransaction().commit();
       
		return loginsList;
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getAllHRUsersFromDB(){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
       session.getTransaction().begin();
        
        List<User> loginsList = new ArrayList<User>();
        loginsList = session.createQuery("from User where type='a' ").list();
        
        session.getTransaction().commit();
       
		return loginsList;
	}
	
	public User getUserById(int id_user){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
       session.getTransaction().begin();
        User user = (User) session.get(User.class, id_user);
        session.getTransaction().commit();
       
		return user;
	}
	
	/**
	 * Sprawdza czy podany login istnieje w bazie
	 * @param login
	 * @return true - jezeli istnieje <br>
	 * false - w przeciwnym wypadku
	 * 
	 */
	public Boolean checkIfLoginExistInDB(String login){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	    session.getTransaction().begin();
	    boolean check = false;
	    String loginDB = (String) session.createSQLQuery("select login from user where login='" + login + "'").uniqueResult();
	    if(loginDB != null){
	    	check = true;
	    }
	    session.getTransaction().commit();
	    return check;
	    
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getUserById_plan(int id_plan){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	    session.getTransaction().begin();
	        
	    List<User> users = session.createQuery("select DISTINCT s.users from SurveyPlan s LEFT JOIN s.users where s.id_plan=" + id_plan).list();
	    	        
	    session.getTransaction().commit();
		return users;
	}
	
	public HashMap<String, String> getNameOfUserByIdUser(int idUserConfirm, int idUserPesel){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	    session.getTransaction().begin();
	    HashMap<String, String> map = new HashMap<String, String>();
	    String confirmUser = (String) session.createSQLQuery("select concat(firstname, ' ', lastname) from user where id_user=" + idUserConfirm).uniqueResult();
	    map.put("confirmUser", confirmUser);
	    String peselUser = "nie podano";
	    String peselUserBD =	(String) session.createSQLQuery("select concat(firstname, ' ', lastname) from user where id_user=" + idUserPesel).uniqueResult();
	    if(peselUserBD != null){
	    	map.put("peselUser", peselUserBD);
	    }else {
	    	map.put("peselUser", peselUser);
		}
	    
	    session.getTransaction().commit();
		return map;
	}
	
}
